#Python's class public members
Object attributes and methods are independent; for example, each cat has its own unique name. However, some things are common to all objects, such as all cats belonging to the species "domestic cat."
In Python, you can create class public members:
- Public attributes are created by defining variables in the class
- Public methods are created as functions without the
self
parameter
Class public members can also be made private by using names with two leading underscores, and can only be accessed through the class's or object's public methods.
# Define class
class Cat:
"""
Cat class
"""
# Public attributes
kingdom = 'Animalia' # Kingdom: Animalia
phylum = 'Chordata' # Phylum: Chordata
class_ = 'Mammalia' # Class: Mammalia (underscore added because 'class' is a Python keyword)
order = 'Carnivora' # Order: Carnivora
family = 'Felidae' # Family: Felidae
genus = 'Felis' # Genus: Felis
species = 'Felis catus' # Species: Domestic cat
# Public method without self parameter
def taxonomy():
print(f"{Cat.kingdom}-{Cat.phylum}")
# Constructor
def __init__(self):
pass
# Create objects
tom = Cat()
garfield = Cat()
# Access public attributes via class and objects
print(Cat.kingdom)
print(tom.kingdom)
print(garfield.kingdom)
# Modify public attribute via class
Cat.kingdom = 'unknown'
print(Cat.kingdom)
print(tom.kingdom)
print(garfield.kingdom)
# Modify attribute via object (creates new instance attribute on tom)
tom.kingdom = 'rat'
print(Cat.kingdom)
print(tom.kingdom)
print(garfield.kingdom)
# Call public method via class
Cat.taxonomy()
# Cannot call method via object because self parameter is automatically passed
try:
garfield.taxonomy()
except:
print("Cannot call garfield.taxonomy()")
This demonstrates how class-level public members work, their shared nature among all instances, and how modifying them via the class or instance affects visibility.